package org.jeecg.modules.demo.points.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.jeecg.modules.customer.entity.BusCustomer;
import org.jeecg.modules.customer.service.IBusCustomerService;
import org.jeecg.modules.demo.points.entity.BusVipPointDetail;
import org.jeecg.modules.demo.points.mapper.BusVipPointDetailMapper;
import org.jeecg.modules.demo.points.service.IBusVipPointDetailService;
import org.jeecg.modules.demo.totalpoints.entity.BusVipPoint;
import org.jeecg.modules.demo.totalpoints.service.IBusVipPointService;
import org.jeecg.modules.message.wechat.FuWuHaoMessageService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * @Description: 积分明细
 * @Author: jeecg-boot
 * @Date: 2021-07-15
 * @Version: V1.0
 */
@Service
public class BusVipPointDetailServiceImpl extends ServiceImpl<BusVipPointDetailMapper, BusVipPointDetail> implements IBusVipPointDetailService {

    @Autowired
    ISysUserService sysUserService;

    @Autowired
    IBusVipPointService vipPointService;

    @Autowired
    FuWuHaoMessageService fuWuHaoMessageService;

    @Autowired
    IBusCustomerService busCustomerService;

    @Override
    public void saveWithMain(BusVipPointDetail busVipPointDetail) {
        String phone = busVipPointDetail.getUserId();
        busVipPointDetail.setUserPhone(phone);
        SysUser sysUser = sysUserService.getUserByPhone(phone);

        busVipPointDetail.setUserId(sysUser.getId());
        save(busVipPointDetail);
        //添加客户积分

        LambdaQueryWrapper<BusVipPoint> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BusVipPoint::getUserId, sysUser.getId());
        BusVipPoint busVipPoint = vipPointService.getOne(wrapper);
        if (busVipPoint == null) {
            busVipPoint = new BusVipPoint();
            busVipPoint.setUserId(sysUser.getId());
            busVipPoint.setPoints(busVipPointDetail.getAmount());
            busVipPoint.setUseablePoints(busVipPointDetail.getAmount());
            vipPointService.save(busVipPoint);

        } else {
            busVipPoint.setPoints(busVipPointDetail.getAmount() + busVipPoint.getPoints());
            busVipPoint.setUseablePoints(busVipPointDetail.getAmount() + busVipPoint.getUseablePoints());
            vipPointService.updateById(busVipPoint);
        }
        LambdaQueryWrapper<BusCustomer> customerLambdaQueryWrapper = new LambdaQueryWrapper<>();
        customerLambdaQueryWrapper.eq(BusCustomer::getSysUserId, sysUser.getId());
        BusCustomer busCustomer = busCustomerService.getOne(customerLambdaQueryWrapper);
        fuWuHaoMessageService.sendPointsMessage("wx7ac6ed39d0d2af6d", busCustomer.getOpenId(), busVipPointDetail, busVipPoint);
    }
}
